package exercise;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-07-16
 * Time: 12:37
 */

/**最小栈:
 * 设计一个支持 push ，pop ，top 操作，并能在常数时间内检索到最小元素的栈。
 * 实现 MinStack 类:
 *
 * MinStack() 初始化堆栈对象。
 * void push(int val) 将元素val推入堆栈。
 * void pop() 删除堆栈顶部的元素。
 * int top() 获取堆栈顶部的元素。
 * int getMin() 获取堆栈中的最小元素。
 *
 *
 * 示例 1:
 *
 * 输入：
 * ["MinStack","push","push","push","getMin","pop","top","getMin"]
 * [[],[-2],[0],[-3],[],[],[],[]]
 *
 * 输出：
 * [null,null,null,null,-3,null,0,-2]
 *
 * 解释：
 * MinStack minStack = new MinStack();
 * minStack.push(-2);
 * minStack.push(0);
 * minStack.push(-3);
 * minStack.getMin();   --> 返回 -3.
 * minStack.pop();
 * minStack.top();      --> 返回 0.
 * minStack.getMin();   --> 返回 -2.
 */
public class Exercise2 {

    static class MinStack {
        public Stack<Integer> minStack;
        public Stack<Integer> stack;
        public MinStack() {
            minStack = new Stack<>();
            stack = new Stack<>();
        }

        @Override
        public String toString() {
            return "MinStack{" +
                    "minStack=" + minStack +
                    ", stack=" + stack +
                    ", top=" + stack +
                    ", getMin=" + minStack +
                    '}';
        }

        //入栈
        public void push(int val) {
            stack.push(val);
            if(minStack.empty()) {
                minStack.push(val);
            }else {
                if(minStack.peek() >= val ) {
                    minStack.push(val);
                }
            }
        }

        //出栈
        public void pop() {
            if(stack.empty()) {
                return;
            }
            int popVal = stack.pop();
            if(popVal == minStack.peek()) {
                minStack.pop();
            }

        }

        //获取普通栈的栈顶元素
        public int top() {
            if(stack.empty()) {
                return -1;
            }
            return stack.peek();
        }

        //获取最小栈的栈顶元素
        public int getMin() {
            if(minStack.empty()) {
                return -1;
            }
            return minStack.peek();
        }

        public static void main(String[] args) {
            /*Stack<String> stack = new Stack<>();
            Stack<String> minStack = new Stack<>();*/

            Exercise2.MinStack minStack = new MinStack();
            minStack.push(-2);
            minStack.push(0);
            minStack.push(-3);
            minStack.getMin();  // --> 返回 -3.
            minStack.pop();
            minStack.top();     //--> 返回 0.
            minStack.getMin();

            System.out.println(minStack);

        }
    }

}
